#include "fifo.h"

int8_t FBCopyFromArray(__IO FIFOBuf* buffer, uint8_t* array, uint8_t n)
{
  uint8_t i;

  if(n > FBGetFreeBytes(buffer))
    return -1;
  if(n > buffer->len)
    return -2;

  for(i = 0; i < n; i++)
  {
    buffer->buf[buffer->wrIdx] = array[i];
    FBPtrInc(buffer, &buffer->wrIdx);
  }
	return 0;
}


/**
  * @brief  FIFO buffer pointer increment
  * @param  buf
  * @param  ptr
  * @retval None
  */
void FBPtrInc (__IO FIFOBuf* buffer, __IO uint8_t* ptr)
{
    *ptr = (*ptr + 1) % buffer->len;
}


/**
  * @brief  FIFO buffer pointer decrement
  * @param  buf
  * @param  ptr
  * @retval None
  */
void FBPtrDec (__IO FIFOBuf* buffer, __IO uint8_t* ptr)
{
    *ptr = (*ptr == 0) ? (buffer->len - 1) : (*ptr - 1);
}

uint8_t FBGetFreeBytes (__IO FIFOBuf* buffer)
{
  if (buffer->rdIdx > buffer->wrIdx)
  {
    return buffer->rdIdx - buffer->wrIdx;
  }
  else
  {
    return buffer->rdIdx + buffer->len - buffer->wrIdx;
  }
}
